package com.colin.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.Serializable;

/**
 * Created by colinx on 2017/6/21.
 */
public class AESOperator implements Serializable {
    private String sKey = "abcdef0123567894";

    private String ivParameter = "012345789abcdef6";

    private static AESOperator instance = null;

    private AESOperator() {
    }

    public static AESOperator getInstance() {
        if (instance == null) {
            instance = new AESOperator();
        }
        return instance;
    }


    public String encrypt(String sSrc){
        String result = "";
        try {
            Cipher cipher;
            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] raw = sKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
            result = DecodeUtils.encodeBytes(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    public String decrypt(String sSrc){
        try {
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = DecodeUtils.decode(sSrc);
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }




    public static void main(String[] args){
        String cSrc = "asd$%#@!$sdffg()*&&*";
        String enString = AESOperator.getInstance().encrypt(cSrc);
        System.out.println(enString);
        String deString = AESOperator.getInstance().decrypt(enString);
        System.out.println(deString);
    }
}
